﻿layui.define(['jquery', 'lscore'], function (exports) {
    "use strict";

    var $ = layui.jquery;
    var lscom = layui.lscore;

    lscom.ajax = function (userOptions) {
        userOptions = userOptions || {};

        var options = $.extend(true, {}, lscom.ajax.defaultOpts, userOptions);
        var oldBeforeSendOption = options.beforeSend;
        options.beforeSend = function (xhr) {
            if (oldBeforeSendOption) {
                oldBeforeSendOption(xhr);
            }

            xhr.setRequestHeader("Pragma", "no-cache");
            xhr.setRequestHeader("Cache-Control", "no-cache");
            xhr.setRequestHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT");
        };

        options.success = undefined;
        options.error = undefined;

        return $.Deferred(function ($dfd) {
            $.ajax(options)
                .done(function (data, textStatus, jqXHR) {
                    //$dfd.resolve(data);
                    //userOptions.success && userOptions.success(data);
                    lscom.ajax.handleResponse(data, userOptions, $dfd, jqXHR);
                }).fail(function (jqXHR) {
                    console.log(jqXHR);
                    lscom.ajax.handleErrorResponse(jqXHR, userOptions, $dfd);
                });
        });
    }

    $.extend(lscom.ajax, {
        defaultOpts: {
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        },

        defaultError: {
            message: '错误提示',
            details: '服务器未发送错误详细信息'
        },

        defaultError401: {
            message: '您没有经过身份验证!',
            details: '您未通过身份验证您应该通过身份验证（登录）才能执行此操作.'
        },

        defaultError403: {
            message: '你没有被授权!',
            details: '您无权执行此操作.'
        },

        defaultError404: {
            message: '找不到资源!',
            details: '在服务器上找不到请求的资源.'
        },

       
        showError: function (error) {
            if (error.details) {
                return layer.alert(error.details, {
                    title: error.message,
                    icon: 2,
                    closeBtn: 0
                });
            } else {
                
                return layer.alert(error.message, {
                    title: lscom.ajax.defaultError.message,
                    icon: 2,
                    closeBtn: 0
                });
            }
        },

        handleTargetUrl: function (targetUrl) {
            if (!targetUrl) {
                location.href = lscom.appPath;
            } else {
                location.href = targetUrl;
            }
        },
        handleErrorResponse: function (jqXHR, userOptions, $dfd) {
            if (userOptions.lsHandleError !== false) {
                switch (jqXHR.status) {
                    case 401:
                        lscom.ajax.showError(lscom.ajax.defaultError401);
                        break;
                    case 403:
                        lscom.ajax.showError(lscom.ajax.defaultError403);
                        break;
                    case 404:
                        lscom.ajax.showError(lscom.ajax.defaultError404);
                        break;
                    default:
                        lscom.ajax.showError(lscom.ajax.defaultError);
                        break;
                }
            }
            //$dfd.reject.apply(this, arguments);
            //userOptions.error && userOptions.error.apply(this, arguments);
            $dfd.reject(jqXHR.responseJSON.message);
            userOptions.error && userOptions.error(jqXHR.responseJSON.message);
        },
        handleResponse: function (data, userOptions, $dfd, jqXHR) {
           
            if (data) {
                if (data.code === 0) {
                    $dfd && $dfd.resolve(data, data, jqXHR);
                    userOptions.success && userOptions.success(data, data, jqXHR);

                    if (data.data && Object.prototype.hasOwnProperty.call(data.data, 'targetUrl')) {
                        lscom.ajax.handleTargetUrl(data.data.targetUrl);
                    }
                } else if (data.code === 1) {
                    console.log(data);
                    if (data.message) {
                        if (userOptions.lsHandleError !== false) {
                            lscom.ajax.showError(data);
                        }
                    } else {
                        data.message = lscom.ajax.defaultError;
                    }
                    $dfd && $dfd.reject(data.message, jqXHR);
                    userOptions.error && userOptions.error(data.message, jqXHR);

                    if (jqXHR.status === 401) {
                        lscom.ajax.handleTargetUrl('/Login/Index');
                    }
                }
            } else { //no data sent to back
                $dfd && $dfd.resolve(jqXHR);
                userOptions.success && userOptions.success(jqXHR);
                if (jqXHR.status === 401) {
                    lscom.ajax.handleTargetUrl('/Login/Index');
                }
            }
        },

        ajaxSendHandler: function (event, request, settings) {
            var token = lscom.security.antiForgery.getToken();
            if (!token) {
                return;
            }

            if (!lscom.security.antiForgery.shouldSendToken(settings)) {
                return;
            }

            if (!settings.headers || settings.headers[lscom.security.antiForgery.tokenHeaderName] === undefined) {
                request.setRequestHeader(lscom.security.antiForgery.tokenHeaderName,"Bearer "+token);
            }
        }
    });

    $(document).ajaxSend(function (event, request, settings) {
        //console.log('ajaxSend')
        //console.log(settings);
        return lscom.ajax.ajaxSendHandler(event, request, settings);
    });

    exports('lsjquery', lscom);
});